package com.vess.ratingweb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;
import javax.mail.MessagingException;
import com.vess.ratingweb.model.JDBCAdapter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Toast;

public class Result extends Activity {

	private ProgressDialog progressDialog;
	private String mStrTimeStamp, mStrLogo, mStrURL, mStrCoupon;
	private CheckBox mCkcSendMail;
	private JDBCAdapter mJDBC;
	private String mStrSubjectMail;
	private String mStrContentMail;
	private String mStrEmail;
	private String mStrEmailPass;
	private String mStrPath;
	private String mStrCustomerEmail;
	private String mStrCustomerName;
	private String mStrThanks;
	private String mStrUsername;
	private int mIntUserId;
	private Mail mail;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.result);

		mCkcSendMail = (CheckBox) findViewById(R.id.chbAgreement);

		mStrTimeStamp = getIntent().getStringExtra("timestamp");
		mStrLogo = getIntent().getStringExtra("logo");
		mStrURL = getIntent().getExtras().getString("url");
		mStrCoupon = getIntent().getStringExtra("coupon");
		mIntUserId = getIntent().getIntExtra("id", 0);

		mJDBC = new JDBCAdapter(Result.this);
		progressDialog = new ProgressDialog(this);
		
		if (mIntUserId != 0) {
			loadUserData();
		}
		
		if (mStrTimeStamp != null) {
			loadSitesReviews();
		}

		new DownloadImageTask((ImageView) findViewById(R.id.imgResultLogo))
				.execute("http://reputation.bonothemes.com/user/php/uploads/"
						+ mStrLogo);

		new DownloadImageTask((ImageView) findViewById(R.id.imgResultCoupon))
				.execute("http://reputation.bonothemes.com/user/php/uploads/"
						+ mStrCoupon);
	}

	private void loadSitesReviews() {
		QuerySitesReviews lp = new QuerySitesReviews();
		lp.execute();
		String strResult = "";
		try {
			strResult = lp.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		if (strResult.equals("-1") == true) {
			Toast.makeText(this, "Can't not to connect to Server!",
					Toast.LENGTH_LONG).show();
		} else {
			if (strResult.equals("0") == true) {
				Toast.makeText(this, "Don't find out information!",
						Toast.LENGTH_LONG).show();
			} else {
				String[] strArrInfo = strResult.split("#@#");

				for (int i = 0; i < strArrInfo.length; i++) {
					mStrUsername = strArrInfo[0];
					mStrCustomerEmail = strArrInfo[4];
					mStrCustomerName = strArrInfo[7];
				}
			}
		}
	}

	private void loadUserData() {
		QueryUserData lp = new QueryUserData();
		lp.execute();
		String strResult = "";
		try {
			strResult = lp.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		if (strResult.equals("-1") == true) {
			Toast.makeText(this, "Can't not to connect to Server!",
					Toast.LENGTH_LONG).show();
		} else {
			if (strResult.equals("0") == true) {
				Toast.makeText(this, "Don't find out information!",
						Toast.LENGTH_LONG).show();
			} else {
				String[] strArrInfo = strResult.split("#@#");

				for (int i = 0; i < strArrInfo.length; i++) {
					mStrThanks = strArrInfo[2];
					mStrSubjectMail = strArrInfo[7];
					mStrContentMail = strArrInfo[8];
					mStrEmail = strArrInfo[9];
					mStrEmailPass = strArrInfo[10];
				}
			}
		}
	}

	public void submitSendMail(View v) {
		String strResult = "";
		if (mCkcSendMail.isChecked()) {
			updateSitesReViewsDB lp = new updateSitesReViewsDB();
			lp.execute();
			try {
				strResult = lp.get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
			if (strResult.equals("-1") == true) {
				Toast.makeText(Result.this, "Can't not to connect to Server!",
						Toast.LENGTH_LONG).show();
			} else {
				mail = new Mail(mStrEmail, mStrEmailPass, this);
				String strRec = mStrCustomerEmail;
				Log.i("Customer Email", mStrCustomerEmail);
				String[] arrayToAccount = strRec.split(";");
				mail.setToAccount(arrayToAccount);
				mail.setFromAccount(mStrEmail);
				mail.setSubject(mStrSubjectMail);
				String strBody = "Dear " + mStrCustomerName + "\n\n" + mStrContentMail + "\n\n" + mStrThanks;
				mail.setBody(strBody);
				File fileCoupon = new File(mStrPath);
				if (fileCoupon.exists()) {
					try {
						mail.attachFile(mStrPath, mStrCoupon);
					} catch (MessagingException e) {
						e.printStackTrace();
					}
				}
				if (mail.send()) {
					progressDialog.dismiss();
					Intent intent = new Intent(this, Welcome.class);
					intent.putExtra("id", mIntUserId);
					intent.putExtra("username", mStrUsername);
					startActivity(intent);
				} else {
					progressDialog.dismiss();
					Toast.makeText(this, "Can't to send email",
							Toast.LENGTH_SHORT).show();
				}
			}
		} else {
			progressDialog.dismiss();
			Intent intent = new Intent(this, Welcome.class);
			intent.putExtra("id", mIntUserId);
			intent.putExtra("username", mStrUsername);
			startActivity(intent);
		}
	}

	private class updateSitesReViewsDB extends
			AsyncTask<String, String, String> {

		private String strResult;

		@Override
		protected String doInBackground(String... params) {
			if (mStrURL == null) {
				strResult = mJDBC.updateSitesReviewsDB(mStrTimeStamp,
						"Lower Rating");
			} else {
				strResult = mJDBC.updateSitesReviewsDB(mStrTimeStamp, mStrURL);
			}
			Log.i("doInBG", strResult);
			return strResult;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}
		
		@Override
		protected void onPreExecute() 
		{
			//
			progressDialog.setTitle("Outbox Mail");
			
			//
			progressDialog.setMessage("Sending...");
			
			progressDialog.setCanceledOnTouchOutside(false);
			
			//
			progressDialog.show();
			super.onPreExecute();
		}
		
	}

	private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
		ImageView bmImage;

		public DownloadImageTask(ImageView bmImage) {
			this.bmImage = bmImage;
		}

		protected Bitmap doInBackground(String... urls) {
			String urldisplay = urls[0];
			Bitmap mIcon11 = null;
			try {
				InputStream in = new java.net.URL(urldisplay).openStream();
				mIcon11 = BitmapFactory.decodeStream(in);
			} catch (Exception e) {
				Log.e("Error", e.getMessage());
				e.printStackTrace();
			}
			return mIcon11;
		}

		protected void onPostExecute(Bitmap result) {
			bmImage.setImageBitmap(result);
			saveImage(result);
		}
	}

	private class QueryUserData extends AsyncTask<String, String, String> {

		private String strResult;

		@Override
		protected String doInBackground(String... params) {
			strResult = mJDBC.selectUserData(mIntUserId);
			Log.i("doInBG", strResult);
			return strResult;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}
	}

	public void saveImage(Bitmap b) {
		String extr = Environment.getExternalStorageDirectory().toString()
				+ "/DCMI";
		File myPath = new File(extr);
		if (!myPath.exists()) {
			myPath.mkdir();
		}

		myPath = new File(extr, mStrCoupon);
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(myPath);
			b.compress(Bitmap.CompressFormat.PNG, 100, fos);
			fos.flush();
			fos.close();
			MediaStore.Images.Media.insertImage(getContentResolver(), b,
					"Screen", "screen");
			mStrPath = myPath.getPath();
			Log.i("path", mStrPath);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private class QuerySitesReviews extends AsyncTask<String, String, String> {

		private String strResult;

		@Override
		protected String doInBackground(String... params) {
			strResult = mJDBC.selectSitesReviews(mStrTimeStamp);
			Log.i("doInBG", strResult);
			return strResult;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}
	}
}
